package com.xudm.cdg.utils;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * markdown工具类
 *
 * @author xudm
 */
@Slf4j
public class MarkdownUtil {
    // 正则表达式，匹配中文字符
    private static final String CHINESE_CHAR_PATTERN = "[\\u4e00-\\u9fa5]";

    /**
     * 提取markdown中的json
     */
    public static String extractJsonFromMarkdown(String markdownText) {
//        String jsonPattern = "```json\\s*(\\{.*?\\})\\s*```";
        String jsonPattern = "```json\\s*([\\s\\S]*?)\\s*```";
        Pattern pattern = Pattern.compile(jsonPattern, Pattern.DOTALL);
//        markdownText = markdownText.replace("\\n", "");
//        markdownText = markdownText.replace("\\", "");
        Matcher matcher = pattern.matcher(markdownText);
        String group = "";
        if (matcher.find()) {
            group = matcher.group(1);
        }
//        Object parse = JSON.parse(group);
//        log.info(JSON.toJSONString(parse));
        return group;
    }

    /**
     * 将json渲染成图片
     *
     * @param jsonString
     * @return
     */
    public static BufferedImage renderJsonToImage(String jsonString) {
        // 设置字体和颜色
        Font font = new Font("Monospaced", Font.PLAIN, 11);
        Color fieldColor = Color.red;
        Color valueColor = Color.GREEN;

        // 创建一个临时图像来计算文本的尺寸
        BufferedImage tempImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = tempImage.createGraphics();
        g2d.setFont(font);

        // 计算图像的宽度和高度
        int width = 0;
        int height = 0;
        for (String line : jsonString.split("\n")) {
            int lineWidth = g2d.getFontMetrics().stringWidth(line);
            width = Math.max(width, lineWidth);
            height += g2d.getFontMetrics().getHeight();
        }
        g2d.dispose();

        // 添加一些边距
        int padding = 20;
        width += padding * 2;
        height += padding * 2;

        // 创建一个实际的图像
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        g2d = image.createGraphics();

        // 设置背景颜色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);

        // 设置字体和颜色
        g2d.setFont(font);

        // 绘制 JSON 文本
        int x = padding;
        int y = padding + g2d.getFontMetrics().getAscent();
        for (String line : jsonString.split("\n")) {
            int colonIndex = line.indexOf(':');
            if (colonIndex != -1) {
                // 绘制字段
                g2d.setColor(fieldColor);
                g2d.drawString(line.substring(0, colonIndex + 1), x, y);

                // 绘制值
                g2d.setColor(valueColor);
                g2d.drawString(line.substring(colonIndex + 1), x + g2d.getFontMetrics().stringWidth(line.substring(0, colonIndex + 1)), y);
            } else {
                // 绘制没有冒号的行（例如花括号）
                g2d.setColor(fieldColor);
                g2d.drawString(line, x, y);
            }
            y += g2d.getFontMetrics().getHeight();
        }

        g2d.dispose();
        return image;
    }

    public static void saveImage(BufferedImage image, String fileName) throws IOException {
        File file = new File(fileName);
        ImageIO.write(image, "png", file);
    }

    public static JsonNode parseJson(String jsonText) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readTree(jsonText);
    }

    public static void main(String[] args) {
        String markdownText = """
                ```json
                                {
                                  "material_district_report": "区县报表",
                                  "district_device_count": 120,
                                  "service_request_info": "服务请求信息",
                                  "user_token": "abc123xyz"
                                }
                                ```
                """;
        String jsonText = extractJsonFromMarkdown(markdownText);
        // 从markdown中提取的json字符串
        if (jsonText != null) {
            try {
                JsonNode jsonData = null;
                jsonData = parseJson(jsonText);
                String jsonString = jsonData.toPrettyString();
                BufferedImage image = renderJsonToImage(jsonString);
                saveImage(image, "json_output.png");
                System.out.println("Image saved as json_output.png");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            System.out.println("No JSON data found in the Markdown text.");
        }
    }

    /**
     * 将BufferedImage转换为OutputStream
     *
     * @param bufferedImage 要转换的BufferedImage
     * @param formatName    图像格式（例如 "png", "jpg"）
     * @return 转换后的OutputStream
     * @throws IOException 如果发生IO错误
     */
    public static InputStream convertBufferedImageToInputStream(BufferedImage bufferedImage, String formatName) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, formatName, outputStream);
        return new ByteArrayInputStream(outputStream.toByteArray());
    }

    /**
     * 将OutputStream写入文件
     *
     * @param outputStream 要写入的OutputStream
     * @param filePath     目标文件路径
     * @throws IOException 如果发生IO错误
     */
    public static void writeOutputStreamToFile(OutputStream outputStream, String filePath) throws IOException {
        try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {
            ((ByteArrayOutputStream) outputStream).writeTo(fileOutputStream);
        }
    }

    public static String[][] parseMarkdownTable(String markdownTable) {
        // 先按行分割
        String[] lines = markdownTable.split("\n");
        // 计算有效行数
        int rowCount = 0;
        for (String line : lines) {
            if (line.startsWith("|")) {
                rowCount++;
            }
        }

        // 初始化二维数组
        String[][] tableData = new String[rowCount][];
        int rowIndex = 0;

        for (String line : lines) {
            if (line.startsWith("|")) {
                // 去掉行首和行尾的竖线，并按竖线分割
                String[] cells = line.substring(1, line.length() - 1).split("\\|");
                // 去掉每个单元格的前后空格
                for (int i = 0; i < cells.length; i++) {
                    cells[i] = cells[i].trim();
                }
                tableData[rowIndex++] = cells;
            }
        }
        return tableData;
    }

    public static boolean containsChinese(String input) {
        Pattern pattern = Pattern.compile(CHINESE_CHAR_PATTERN);
        Matcher matcher = pattern.matcher(input);
        return matcher.find();
    }

}
